from django.shortcuts import render

# Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from s3upload.models import Document
from s3upload.forms import DocumentForm
from s3upload.tasks import add,s3up
from time import gmtime, strftime

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            #print newdoc.docfile._get_path()
            filename = newdoc.docfile._get_path()
            tmp = filename.split('/')
            nowtime = strftime("documents/%Y/%m/%d", gmtime())
            tmp.insert(len(tmp)-1,nowtime)
            filename = '/'.join(tmp)
            print filename
            newdoc.save()
            result = s3up.delay(filename)
            print result.ready()
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('s3upload.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
